package io.renren.sf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.ResponseData;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.sf.entity.BookRoleEntity;
import io.renren.sf.entity.TeacherEntity;
import io.renren.sf.entity.TeacherRoleEntity;
import io.renren.sf.service.TeacherRoleService;
import io.renren.sf.service.TeacherService;
import io.renren.sf.vo.TeacherRoleSaveVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@RestController
@Api(tags = "用户管理", hidden = true)
@RequestMapping("sf/teacher")
@ApiIgnore
public class TeacherController extends AbstractController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeacherRoleService teacherRoleService;

    @GetMapping("/info/{teacherId}")
    public R info(@PathVariable("teacherId") Long teacherId) {
        TeacherEntity teacher = teacherService.getById(teacherId);

        //获取用户所属的课本角色列表
        List<Long> roleIdList = teacherRoleService.getRoleIds(teacherId);
        teacher.setBookRoleIds(roleIdList);

        return R.ok().put("teacher", teacher);
    }

    @PostMapping("/saveTeacherRole")
    public R saveTeacherRole(@RequestBody TeacherRoleSaveVo teacherRoleSaveVo) {
        teacherRoleService.remove(new QueryWrapper<TeacherRoleEntity>().eq("tid", teacherRoleSaveVo.getId()));
        List<TeacherRoleEntity> teacherRoles = new ArrayList<>();
        List<Long> bookRoleIds = teacherRoleSaveVo.getBookRoleIds();
        for (Long bookRoleId : bookRoleIds) {
            TeacherRoleEntity teacherRole = new TeacherRoleEntity();
            teacherRole.setRid(bookRoleId);
            teacherRole.setTid(teacherRoleSaveVo.getId());
            teacherRoles.add(teacherRole);
        }
        teacherRoleService.saveBatch(teacherRoles);
        return R.ok();
    }

    @Transactional
    @ApiOperation(value = "批量新增用户", produces = "application/octet-stream")
    @PostMapping("/saveBatchTeacher")
    public void saveBatchTeacher(@RequestBody List<TeacherEntity> teacherList, HttpServletResponse response) {
        StringBuilder sb = new StringBuilder();
        for (TeacherEntity teacher : teacherList) {
            Integer num = teacher.getNum();
            Integer start = teacher.getStart();
            String password = teacher.getPassword();
            for (int i = 0; i < num; i++) {
                String mobile = teacher.getMobile() + (start + i);
                String newPassWord = StringUtils.isEmpty(password) ? mobile : password;
                sb.append("账号：").append(mobile).append("\t").append("密码：").append(newPassWord).append("\n");
                newPassWord = new BCryptPasswordEncoder().encode(newPassWord);
                TeacherEntity newTeacher = new TeacherEntity();
                newTeacher.setCampusId(teacher.getCampusId()).setMobile(mobile).setPassword(newPassWord).setMacStatus(1).setCreatetime(new Date()).setUserType(2).setStatus(1).setStoptime(teacher.getStoptime());
                teacherService.save(newTeacher);
                List<TeacherRoleEntity> teacherRoleList = new ArrayList<>();
                for (Long roleId : teacher.getBookRoleIds()) {
                    TeacherRoleEntity teacherRole = new TeacherRoleEntity();
                    teacherRole.setRid(roleId).setTid(newTeacher.getId());
                    teacherRoleList.add(teacherRole);
                }
                teacherRoleService.saveBatch(teacherRoleList);
            }
        }
        // 导出txt
        exportTeacherText(response, sb);
    }

    public String exportTeacherText(HttpServletResponse response, StringBuilder sb) {
        try {
            // 创建文件流
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String currentDate = simpleDateFormat.format(new Date());
            String filename = "账号列表" + "_" + currentDate;
            File tmpFile = new File(filename);
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
            tmpFile.createNewFile();
            BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile));
            bw.write(sb.toString());
            bw.flush(); // 清除缓存
            bw.close();

            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(tmpFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            bis.close();
            fis.close();
            //删除文件
            tmpFile.delete();
        } catch (IOException e) {
            log.error(Arrays.toString(e.getStackTrace()));
        }
        return null;
    }
}
